<?php
defined('SYSPATH') or die('No direct script access.');

abstract class Model_Base extends ORM{
	public $total_count;
	public function search($filters){
		return $this->getResult($filters);
	}
	
	protected function getResult($filters){
		if (array_key_exists("page", $filters)){
			$result = $this->getResultByPagination($filters);
		}else{
			$result = $this->modelWithCondition($filters)->find_all();
		}
		return $result;
	}

	private function getResultByPagination($filters){
		$attrArray["total_items"] = $this->getResultCount($this->modelWithCondition($filters));
		$this->total_count = $attrArray["total_items"];
		$page = $filters["page"];
		if (array_key_exists("pageSize", $filters)){
			$attrArray["items_per_page"] = $filters["pageSize"];
		}
		$pagination = Pagination::factory($attrArray);
		if ($page <= $pagination->total_pages){
			$result = $this->modelWithCondition($filters)->limit($pagination->items_per_page)->offset($pagination->offset)->find_all();
		}
		else{
			$result = array();
		}
		return $result;
	}
	
	private function getResultCount($model){
		return $model->count_all();
	}
	
	protected function convertToUtf8($value){
		if (!$this->iS_Utf8($value)){
			return mb_convert_encoding($value, "utf-8", "gb2312");
		}
		return $value;
	}
	
	protected function iS_Utf8($value)
	{
		if (preg_match("/^([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}/",$value) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}$/",$value) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){2,}/",$value) == true)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	public function deleteAll($selectedIds){
		$status = "I";
		$this->status = $status;
		$this->updatetime = Date::formatted_time();
		$ids = $selectedIds;
		foreach (split(",", $ids) as $id){
			if (!empty($id)){
				$this->or_where("id","=",$id);
			}
		}
		return $this->save_all();
	}
	
	protected abstract function modelWithCondition($filters);
}